package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.bimq.BiProducer;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.MqConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RedisLimiterMananger;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.model.vo.LoginUserVO;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.SqlUtils;
import io.netty.util.concurrent.CompleteFuture;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 帖子接口
 *
 *
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    private final static Gson GSON = new Gson();

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterMananger redisLimiterMananger;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiProducer biProducer;

    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(chart.getId());
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<Chart>> listChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        User user = userService.getLoginUser(request);
        Page<Chart> chartPage = chartService.getChartByPageByRedis(chartQueryRequest, user);
//        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
//                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<Chart>> listMyChartVOByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        User user = userService.getLoginUser(request);
        Page<Chart> chartPage = chartService.getChartByPageByRedis(chartQueryRequest, user);

        return ResultUtils.success(chartPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }

        Long id = chartQueryRequest.getId();;
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String charType = chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id > 0, "id", id);
        queryWrapper.eq(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(goal), "goal", goal);
        queryWrapper.eq(StringUtils.isNotBlank(charType), "charType", charType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);

        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
    * ai 分析
    */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                             GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        // 验参
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();
        String chartType = genChartByAiRequest.getChartType();

        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotEmpty(name) && name.length() >= 80, ErrorCode.PARAMS_ERROR, "图表名称过长");

        // 文件大小和后缀的校验
        Long userSubmitFileSize = multipartFile.getSize();
        String userSubmitFileName = multipartFile.getOriginalFilename();
        String userSubmitFileSuffix = FileUtil.getSuffix(userSubmitFileName);

        final long USER_SUBMIT_FILE_LIMIT_SIZE = 1024 * 1024L;
        ThrowUtils.throwIf(userSubmitFileSize > USER_SUBMIT_FILE_LIMIT_SIZE, ErrorCode.PARAMS_ERROR, "文件大小超过 1 M");
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!validFileSuffixList.contains(userSubmitFileSuffix), ErrorCode.PARAMS_ERROR, "传入文件不合法，请传入正确的 excel 文件");

        User loginUser = userService.getLoginUser(request);

        // 限流判断
        redisLimiterMananger.doRateLimit("genChartByAi_" + loginUser.getId());

        // 解析并压缩 excel
        String csvData = ExcelUtils.excelToCsv(multipartFile);

        // 根据预定格式封装用户输入信息
        StringBuilder userInput = new StringBuilder();
        Long modelId = 1686630339541315586L;
        userInput.append("分析需求：\n");

        if(StringUtils.isNotBlank(chartType)){
            goal += "，请使用" + chartType + "的图表类型生成数据";
        }

        userInput.append(goal).append("\n");
        userInput.append("原始数据：\n");
        userInput.append(csvData).append("\n");

        // 获取 Bi 结果并校验
        String result = aiManager.doChat(userInput.toString(), modelId);
        String[] resultArr = result.split("【【【【");

        if(resultArr.length < 3){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }

        // 保存结果到数据库
        String genChart = resultArr[1].trim();
        String genResult = resultArr[2].trim();

        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        chart.setStatus("succeed");

        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult,ErrorCode.SYSTEM_ERROR,"图表保存失败");

        // 数据库发生变化，保证双写一致性
        biProducer.sendRedisMySQLConsistMessage(loginUser.getId() + "");

        // 返回分析结果
        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    /**
    * ai 分析-异步
    */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        // 验参
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();
        String chartType = genChartByAiRequest.getChartType();

        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotEmpty(name) && name.length() >= 80, ErrorCode.PARAMS_ERROR, "图表名称过长");

        // 文件大小和后缀的校验
        Long userSubmitFileSize = multipartFile.getSize();
        String userSubmitFileName = multipartFile.getOriginalFilename();
        String userSubmitFileSuffix = FileUtil.getSuffix(userSubmitFileName);

        final long USER_SUBMIT_FILE_LIMIT_SIZE = 1024 * 1024L;
        ThrowUtils.throwIf(userSubmitFileSize > USER_SUBMIT_FILE_LIMIT_SIZE, ErrorCode.PARAMS_ERROR, "文件大小超过 1 M");
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!validFileSuffixList.contains(userSubmitFileSuffix), ErrorCode.PARAMS_ERROR, "传入文件不合法，请传入正确的 excel 文件");

        User loginUser = userService.getLoginUser(request);

        // 限流判断
        redisLimiterMananger.doRateLimit("genChartByAi_" + loginUser.getId());

        // 解析并压缩 excel
        String csvData = ExcelUtils.excelToCsv(multipartFile);

        // 保存结果到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        // 异步待生成
        // chart.setGenChart(genChart);
        // chart.setGenResult(genResult);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        chartService.save(chart);

        // 根据预定格式封装用户输入信息
        StringBuilder userInput = new StringBuilder();
        Long modelId = 1686630339541315586L;
        userInput.append("分析需求：\n");

        if(StringUtils.isNotBlank(chartType)){
            goal += "，请使用" + chartType + "的图表类型生成数据";
        }

        userInput.append(goal).append("\n");
        userInput.append("原始数据：\n");
        userInput.append(csvData).append("\n");

        // 异步调用 ai 生成分析结果
        CompletableFuture.runAsync(()->{
            // 更改状态为执行中
            Chart updateChartStatus = new Chart();
            updateChartStatus.setId(chart.getId());
            updateChartStatus.setStatus("running");
            chartService.updateById(updateChartStatus);

            // 获取 Bi 结果并校验
            String result = aiManager.doChat(userInput.toString(), modelId);
            String[] resultArr = result.split("【【【【");

            if(resultArr.length < 3){
                handleChartUpdateError(chart.getId(), "ai 生成异常");
                return;
            }

            String genChart = resultArr[1].trim();
            String genResult = resultArr[2].trim();

            // 更新数据库，更改状态为成功
            Chart updateChartResult = new Chart();
            updateChartResult.setId(chart.getId());
            updateChartResult.setGenChart(genChart);
            updateChartResult.setGenResult(genResult);
            updateChartResult.setStatus("succeed");
            boolean updateResult = chartService.updateById(updateChartResult);

            if(!updateResult){
                handleChartUpdateError(chart.getId(), "更新数据库状态失败");
            }
        }, threadPoolExecutor);

        // 返回分析结果
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }


    /**
     * ai 分析-异步
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        // 验参
        String goal = genChartByAiRequest.getGoal();
        String name = genChartByAiRequest.getName();
        String chartType = genChartByAiRequest.getChartType();

        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "分析目标为空");
        ThrowUtils.throwIf(StringUtils.isNotEmpty(name) && name.length() >= 80, ErrorCode.PARAMS_ERROR, "图表名称过长");

        // 文件大小和后缀的校验
        Long userSubmitFileSize = multipartFile.getSize();
        String userSubmitFileName = multipartFile.getOriginalFilename();
        String userSubmitFileSuffix = FileUtil.getSuffix(userSubmitFileName);

        final long USER_SUBMIT_FILE_LIMIT_SIZE = 1024 * 1024L;
        ThrowUtils.throwIf(userSubmitFileSize > USER_SUBMIT_FILE_LIMIT_SIZE, ErrorCode.PARAMS_ERROR, "文件大小超过 1 M");
        final List<String> validFileSuffixList = Arrays.asList("xlsx", "xls");
        ThrowUtils.throwIf(!validFileSuffixList.contains(userSubmitFileSuffix), ErrorCode.PARAMS_ERROR, "传入文件不合法，请传入正确的 excel 文件");

        User loginUser = userService.getLoginUser(request);

        // 限流判断
        redisLimiterMananger.doRateLimit("genChartByAi_" + loginUser.getId());

        // 解析并压缩 excel
        String csvData = ExcelUtils.excelToCsv(multipartFile);

        // 保存结果到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus("wait");
        chart.setUserId(loginUser.getId());
        chartService.save(chart);

        // 将 chart id 作为消息传入到消息队列中
        biProducer.sendMessage(String.valueOf(chart.getId()));

        // 返回分析结果
        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    /**
     * 更新数据库状态发生异常
     */
    private void handleChartUpdateError(Long chartId, String execMessage){
        Chart updateChartError = new Chart();
        updateChartError.setId(chartId);
        updateChartError.setStatus("failed");
        updateChartError.setExecMessage(execMessage);

        boolean updateChartErrorResult = chartService.updateById(updateChartError);
        if(!updateChartErrorResult){
            log.error("更新图表失败状态未成功" + chartId + "," + execMessage);
        }
    }
}
